import React from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import { Link } from 'dva/router';
import {Button,Row,Col,Layout, Modal,InputNumber, Breadcrumb,Select,Icon,Form,Input,Affix,DatePicker,message,Cascader} from 'antd';
import reqwest from 'reqwest';
import style from '../../styles/ResetInput.less';
import inStyle from '../../styles/Info.less'
import {numvail,selectvail,mathvail} from '../../utils/Validator.js'
import {disabledStartDate,disabledEndDate} from '../../utils/Date.js'
import CityPick from '../../components/CityPick.js';
import moment from 'moment';
import options from '../../models/CityData.js';
const FormItem = Form.Item;
const Option =Select.Option;

class Strate extends React.Component{
	constructor(props){
		super(props);
    this.edit = this.props.location.query.initv == '无敌' ? JSON.parse(sessionStorage['edit']) : null;
    console.log('this.edit', this.edit)
		this.state={
			startValue: this.edit.end_at==null?null:moment(this.edit.start_at, 'YYYY-MM-DD HH:mm:ss'),
	    endValue: this.edit.start_at==null?null:moment(this.edit.end_at, 'YYYY-MM-DD HH:mm:ss'),
	    endOpen: false,
	    list:[],
	    // option:sessionStorage['store_tree']==('undefined'||undefined)?[]:JSON.parse(sessionStorage['store_tree']),
	    option:[],
      loading:false,
      stores: [],
	    vali_status_1: "success",
	    vali_status_2: "success",
	    vali_status_3: "success",
		}
	}
	getServer(){
		reqwest({
      url: window.host+'/api/pres',
      method: 'get',
      crossOrigin: true,
	    // headers:AUTH_KEY,
  	  // contentType: 'application/json',
  	  data:{
  	  	access_token:window.localStorage['token']
  	  },
      type: 'json',
    }).then((data) => {
    	console.log(data);
    	this.setState({option:data.regions})
    }).fail( (err, msg) =>{
       console.log(1)
       // this.setState({loading:true});
    })
	}
	disabledStartDate(startValue){
    const endValue = this.state.endValue;
    if (!startValue || !endValue) {
      return false;
    }
    return startValue.valueOf() > endValue.valueOf();
  }

  disabledEndDate(endValue){
    const startValue = this.state.startValue;
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  }

  onChange(field, value){
    this.setState({
      [field]: value,
    });
  }

  onStartChange(value){
    this.onChange('startValue', value);
  }

  onEndChange(value){
    this.onChange('endValue', value);
  }

  handleStartOpenChange(open){
    if (!open) {
      this.setState({ endOpen: true });
    }
  }

  handleEndOpenChange(open){
    this.setState({ endOpen: open });
  }
  handleCityChange(e,obj){
  	this.setState({
  		province:obj[0]==undefined?undefined:obj[0].label,
  		city:obj[1]==undefined?undefined:obj[1].label,
  		area:obj[2]==undefined?undefined:obj[2].label,
  		// street:obj[3]==undefined?undefined:obj[3].label
  	})
  }
	handleSubmit(e){
    // console.log(e)
    e.preventDefault();
    let _this=this;
    this.props.form.validateFields((err, values) => {
        console.log(values);
      if (!err ) {
        console.log('Received values of form: ', values);
	      	_this.patchserver({
	      	 	value:values
	      	})

      }else{
      	console.log(2)
      }
    });
	}
	componentWillMount(){
    // console.log(sessionStorage['edit'])
    let _this = this;
    _this.getStoreValue(_this.edit.regions_id, true);
		_this.getServer();
	}
	patchserver(params={}){
		this.setState({loading:true});
		console.log(params)
		let _this = this
		// const {province,city,area} = this.state;
		reqwest({
      url: window.host + '/api/strategies/' + _this.edit.id,
      method: 'post',
      crossOrigin: true,
      data:{
        access_token:localStorage['token'],
        strategy:{
          title:params.value.theme,
        	start_at:params.value.start_at,end_at:params.value.end_at,
          region_id:params.value.store,
          store_id: params.value.store_id,
          // province:params.value.city[0],
          // city:params.value.city[1],
          // area:params.value.city[2],
          rate:params.value.rate/100,
          discount:params.value.discount/100,
          rebate:params.value.rebate/100,
          pound:params.value.pound
        },
        remark:params.remark,
      },
      type: 'json',
    }).then((data) => {
      console.log(data);
      if(data.status=='success'){
      	message.success('更新成功', 1.5,()=>{
     		  window.location.hash='/app/strategies?current='+_this.props.location.query.current;
      	});
      }else{
      	message.warning(data.msg,0.5)
      	this.setState({loading:false});
      	message.error(data.msg,0.5)
      }
    }).fail( (err, msg) =>{
    	this.setState({loading:false});
       console.log(1)
    })
  }
  getStoreValue(e, bool) {
    let _this = this;
    reqwest({
      url: window.host + '/api/regions/' + e,
      method: 'get',
      crossOrigin: true,
      data: {
        access_token: localStorage['token']
      },
      type: 'json'
    }).then((data) => {
      if (data.status === 'success') {
        if (!bool) _this.edit.store_id = null
        _this.setState({ stores: data.stores })
      }
    })
  }
	render(){
		const { startValue, endValue, endOpen, list, option, stores } = this.state;
		// console.log(this.edit.address)
		let _this =this;
		const formItemLayout = {
      labelCol: { span: 7},
      wrapperCol: { span: 17 },
      style:{minWidth:200}
    };
    const _option = option.map(function(data){
    	return <Option value={''+data.id} key={'a'+data.id}>{data.name}</Option>
    })
    const _store_option = stores.map(store => {
      return <Option value={ '' + store.id } key={ '' + store.id }>{ store.name }</Option>
    })
  	const {getFieldDecorator}=this.props.form;
		return(
			<Layout >
				<Layout.Content className={`${style.berad}`} >
					<Row>
						<Breadcrumb  className={`${style.blue_dia_none}`}>
							<Breadcrumb.Item ><span className={`${style.blue_dia}`}></span></Breadcrumb.Item>
              <Breadcrumb.Item className={`${style.bread_div} ${style.bread_div_first}`}><Link to={{pathname:'/app/strategies',query:{current:this.props.location.query.current}}}>策略</Link></Breadcrumb.Item>
              <Breadcrumb.Item className={`${style.bread_div}`}>编辑策略</Breadcrumb.Item>
	       		</Breadcrumb>
	       	</Row>
				</Layout.Content>
				<Layout style={{background:'#fff'}}>
				<Form hideRequiredMark={false} className={`${inStyle.ncc_left_layout}`} onSubmit={this.handleSubmit.bind(this)}>
       		<Row style={{marginTop:26}}>
	       		<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem  {...formItemLayout}  label='主题'>
								{getFieldDecorator('theme',{
									initialValue:this.edit==null?null:this.edit.title,
									rules:[{message:'请定制你的主题'}]
								})(
									<Input className={`${style.ncc_reset_input}`} placeholder='主题' />
								)}
							</FormItem>
						</Col>
					</Row>
					<Row>
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem  {...formItemLayout}  label='渠道'>
								{getFieldDecorator('store',{
									initialValue:this.edit.regions_id==null?undefined:''+this.edit.regions_id,
                  rules:[{message:'请选择渠道'}],
								})(
									<Select dropdownClassName={`${style.ncc_select_down}`} placeholder='渠道'  default className={`${style.ncc_reset_border}`} onChange={this.getStoreValue.bind(this)} optionFilterProp='children' showSearch>
										{_option}
									</Select>
								)}
							</FormItem>
						</Col>
					</Row>
          <Row>
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem  {...formItemLayout}  label='商铺'>
								{getFieldDecorator('store_id',{
									initialValue:this.edit.store_id==null?undefined:''+this.edit.store_id,
                  rules:[{message:'请选择商铺'}],
								})(
									<Select dropdownClassName={`${style.ncc_select_down}`} placeholder='商铺'  default className={`${style.ncc_reset_border}`} optionFilterProp='children' showSearch>
                    { _store_option }
									</Select>
								)}
							</FormItem>
						</Col>
					</Row>
					<Row>
	       		<Col sm={{span :8,pull:0}} xs={{span:24,pull:3}} className={`${style.reset_col}`}>
							<FormItem {...formItemLayout} label={<span>开始时间</span>}  className={`${style.date_reset_input}`}>
								{getFieldDecorator('start_at',{
									initialValue:startValue,
									rules:[{message:'请输入时间',validator:(rule,value,callback)=>{
										selectvail(rule,value,callback,rule.message);
									}}]
								})(
									<DatePicker
					          disabledDate={this.disabledStartDate.bind(this)}
					          format='YYYY-MM-DD HH:mm:ss'
					          showTime
					          placeholder="开始时间"
					          onChange={this.onStartChange.bind(this)}
					          onOpenChange={this.handleStartOpenChange.bind(this)}
					        />
								)}
							</FormItem>
						</Col>
						<Col sm={{span :8,pull:0}} xs={{span:24,pull:3}} lg={{pull:2}} xl={{pull:3}}  className={`${style.reset_col}`}>
							<FormItem {...formItemLayout} label='结束时间'  className={`${style.date_reset_input} ${style.date_reset_input_end}`}>
								{getFieldDecorator('end_at',{
									initialValue:endValue,
									rules:[{message:'请输入时间',validator:(rule,value,callback)=>{
										selectvail(rule,value,callback,rule.message);
									}}]
								})(
									<DatePicker
					          disabledDate={this.disabledEndDate.bind(this)}
					          format='YYYY-MM-DD HH:mm:ss'
					          showTime
					          placeholder="结束时间"
					          onChange={this.onEndChange.bind(this)}
					          onOpenChange={this.handleEndOpenChange.bind(this)}
					        />
								)}
							</FormItem>
						</Col>
					</Row>
					{/* <Row >
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}}>
							<FormItem {...formItemLayout} label='地址'>
								{getFieldDecorator('city',{
									initialValue:this.edit==null?null:this.edit.address,
									rules:[{message:'请选择地址',validator:(rule,value,callback)=>{
										callback();
									}}]
								})(
									<Cascader className={`${style.ncc_reset_input}`} onChange={this.props.onChange}  style={{border:'none'}} options={options}  showSearch  placeholder='省市区' />
								)}
							</FormItem>
						</Col>
					</Row> */}
					<Row >
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem validateStatus={this.state.vali_status_1} help={this.state.vali_status_1=="success"?undefined:'已超过10%'} {...formItemLayout} label='销售提成(%)' className={`${style.reset_before_span}`} >
								{getFieldDecorator('rate',{
									initialValue:this.edit==null?null:this.edit.rate*100,
									rules:[{pattern:/\d+/,message:'请输入销售提成',validator(rule,value,callback){
										if(value<=100||value>0){
											if(value>10){
												// callback.message('警告')
												_this.setState({vali_status_1:'warning'})
												callback()
												return;
											}
											_this.setState({vali_status_1:'success'})
											callback()
										}else{
											callback('请输入销售提成(1%~100%)')
										}
									}}],
								})(
									<Input min={0} type='number' max={100} className={`${style.ncc_reset_input}`} placeholder='请输入销售提成(1%~100%)' />
								)}
							</FormItem>
						</Col>
					</Row>
					<Row>
						<Col  className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem validateStatus={this.state.vali_status_2} help={this.state.vali_status_2=="success"?undefined:'已超过10%'} {...formItemLayout} label='折扣(%)' className={`${style.reset_before_span}`} >
								{getFieldDecorator('discount',{
									initialValue:this.edit==null?null:this.edit.discount*100,
									rules:[{pattern:/^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$/,message:'请输入折扣(%)',validator(rule,value,callback){
										if(value<=100||value>0){
											if(value>10){
												// callback.message('警告')
												_this.setState({vali_status_2:'warning'})
												callback()
												return;
											}
											_this.setState({vali_status_2:'success'})
											callback()
										}else{
											callback('请输入提成(1%~100%)')
										}
									}}]
								})(
									<Input min={0} type='number' max={100} className={`${style.ncc_reset_input}`} placeholder='请输入折扣(1%~100%)' />
								)}
							</FormItem>
						</Col>
					</Row>
					<Row>
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}}  >
							<FormItem validateStatus={this.state.vali_status_3} help={this.state.vali_status_3=="success"?undefined:'已超过10%'} {...formItemLayout} label='介绍费(%)' className={`${style.reset_before_span}`}>
								{getFieldDecorator('rebate',{
									initialValue:this.edit==null?null:this.edit.rebate*100,
									rules:[{message:'请输入介绍人介绍费',validator(rule,value,callback){
										// mathvail(rule,value,callback)
										if(value<=100||value>0){
											if(value>10){
												// callback.message('警告')
												_this.setState({vali_status_3:'warning'})
												callback()
												return;
											}
											_this.setState({vali_status_3:'success'})
											callback()
										}else{
											callback('请输入提成(1%~100%)')
										}
									}}]
								})(
									<Input min={0} type='number' max={100} className={`${style.ncc_reset_input}`} placeholder='介绍人介绍费(1%~100%)' />
								)}
							</FormItem>
						</Col>
					</Row>
					<Row>
						<Col  className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem extra='数字越大优先级越高' {...formItemLayout} label='优先级' >
								{getFieldDecorator('pound',{
									initialValue:this.edit==null?null:this.edit.pound,
									// rules:[{pattern:/^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$/,message:'请输入策略优先级',validator(rule,value,callback){
									// 	mathvail(rule,value,callback)
									// }
									// }]
								})(
									<Input type='number'  className={`${style.ncc_reset_input}`} placeholder='请输入策略优先级' />
								)}
							</FormItem>
						</Col>
					</Row>
       		<Row>
	       		<Col xl={{offset:3}} lg={{offset:2}} sm={{span :8,pull:0}} xs={{span:17,pull:3}}  >
		       		<div  style={{float:'left'}} >
		       			<FormItem >
			            <Button loading={this.state.loading} htmlType="submit" size='large' type="primary"  >
			              保存
			            </Button>
		          	</FormItem>
		          </div>
		          <div  style={{float:'left',marginLeft:10}} >
		          	<Button size='large'  >
			              <Link to={{pathname:'/app/strategies',query:{current:this.props.location.query.current}}}>取消</Link>
			          </Button>
		          </div>
	          </Col>
          </Row>
				</Form>
			</Layout>
			</Layout>
		)
	}
}

//<Col span={24}>
// 	<Breadcrumb style={{ height:60,lineHeight:'60px',fontSize:14,marginTop:20}}>
//          <Breadcrumb.Item>备注<span style={{fontSize:12}}>(选填项)</span></Breadcrumb.Item>
//    		</Breadcrumb>
//   		</Col>
//   		<Row>
//   		<Col className={`${style.reset_col}`} sm={{span :17,pull:0}} xs={{span:17,pull:0}}  >
// 		<FormItem >
// 		{getFieldDecorator('remark',{
// 			initialValue:this.edit.remark
// 		})(
// 			<Input type='textarea' className={`${style.ncc_reset_input} `} placeholder='备注:' />
// 		)}
// 	</FormItem>
// </Col>
//</Row>
const EditStrate = Form.create()(Strate);

export default connect()(EditStrate);
